package com.shishuo.cdn.action;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shishuo.cdn.constant.OrderCode;
import com.shishuo.cdn.dao.ContractDao;
import com.shishuo.cdn.dao.OrderDao;
import com.shishuo.cdn.dao.UserBankLogDao;
import com.shishuo.cdn.dao.UserDao;
import com.shishuo.cdn.entity.User;
import com.shishuo.cdn.entity.vo.JsonVo;
import com.shishuo.cdn.util.CommonUtil;
/**
 * 订单管理
 * @author liaoliyun
 *  
 *
 */
@Controller
@RequestMapping("/order")
public class OrderAction extends BaseAction {
	
	private static final int DEFAULT_COUNT_ONEPAGE=4;//默认每页显示条数
	
	@Autowired
	private UserBankLogDao userBankLogDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private ContractDao contractDao;	
	@ResponseBody
	@RequestMapping(value = "/addIspOrder.json", method = RequestMethod.POST)
	public JsonVo<String> addIspOrder(HttpServletRequest request, ModelMap modelMap) throws ParseException{
		createParameterMap(request);
		String orderNum;
		User user=(User)request.getSession().getAttribute("user");
		
		paramsMap.put("user_name", request.getParameter("user_name")); //createParameterMap 不能转换中文
		paramsMap.put("user_addr", request.getParameter("user_addr")); //createParameterMap 不能转换中文
		paramsMap.put("user_addr2", request.getParameter("user_addr2")); //createParameterMap 不能转换中文
		paramsMap.put("user_addr3", request.getParameter("user_addr3")); //createParameterMap 不能转换中文
		paramsMap.put("ISP_speed", request.getParameter("ISP_speed").replace("M", ""));

		paramsMap.put("user_id", user.getReg_tel());
		
		paramsMap.put("type", "ISP");
		
		paramsMap.put("status", 0);
		String start_time=request.getParameter("start_time");
		SimpleDateFormat sd=new SimpleDateFormat("MM/dd/yyyy");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date old=sd.parse(start_time);
		paramsMap.put("start_time", sdf.format(old));
//		paramsMap.put("order_span", 1);
//		paramsMap.put("ISP_type", 1);
//		paramsMap.put("ISP_speed", 20);
		paramsMap.put("cost_money", Double.valueOf(paramsMap.get("cost_money").toString()));
		Date create_time = new Date();
		paramsMap.put("create_time", create_time);
		if("".equals(paramsMap.get("buy_IP").toString()))paramsMap.put("buy_IP", 0);
		orderDao.addIspOrder(paramsMap);
		//当前日期（4位）+产品编号（5位）+序列号（3位）。如：022110000001
		String id = paramsMap.get("order_id").toString();
		if(id.length() == 1){
			id="00"+id;
		}else if (id.length() ==2){
			id="0"+id;
		}
		sdf=new SimpleDateFormat("MMdd");
		orderNum =sdf.format(create_time)+ OrderCode.ISP_CODE.getId() + id;		
//		orderNum ="ISP"+ user.getReg_tel() + "_"+paramsMap.get("order_id").toString();
		paramsMap.put("order_num", orderNum);
		orderDao.updateIspOrderNumById(paramsMap);
		json.setResult(true);
		
		return json;
	
	}

	@ResponseBody
	@RequestMapping(value = "/addIdcOrder.json", method = RequestMethod.POST)
	public JsonVo<String> addIdcOrder(@RequestParam(value = "user_name") String user_name,HttpServletRequest request, ModelMap modelMap) throws ParseException{
		createParameterMap(request);
		String orderNum;
		User user=(User)request.getSession().getAttribute("user");
		if("".equals(paramsMap.get("jijia_count")))paramsMap.put("jijia_count", 0);
		paramsMap.put("user_name", request.getParameter("user_name")); //createParameterMap 不能转换中文
		paramsMap.put("user_addr", request.getParameter("user_addr")); //createParameterMap 不能转换中文
		paramsMap.put("user_addr2", request.getParameter("user_addr2")); //createParameterMap 不能转换中文
		paramsMap.put("user_addr3", request.getParameter("user_addr3")); //createParameterMap 不能转换中文
		paramsMap.put("IDC_speed", request.getParameter("IDC_speed").replace("M", ""));
		paramsMap.put("user_id", user.getReg_tel());
		
		paramsMap.put("type", "IDC");
		
		paramsMap.put("status", 0);
		String start_time=request.getParameter("start_time");
		SimpleDateFormat sd=new SimpleDateFormat("MM/dd/yyyy");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date old=sd.parse(start_time);
		paramsMap.put("start_time", sdf.format(old));
//		paramsMap.put("order_span", 1);
//		paramsMap.put("IDC_type", 1);
//		paramsMap.put("IDC_speed", 20);
		paramsMap.put("cost_money", Double.valueOf(paramsMap.get("cost_money").toString()));
		Date create_time = new Date();
		paramsMap.put("create_time", create_time);
		if("".equals(paramsMap.get("buy_IP").toString()))paramsMap.put("buy_IP", 0);
		orderDao.addIdcOrder(paramsMap);
		//当前日期（4位）+产品编号（5位）+序列号（3位）。如：022110000001
		String id = paramsMap.get("order_id").toString();
		if(id.length() == 1){
			id="00"+id;
		}else if (id.length() ==2){
			id="0"+id;
		}
		sdf=new SimpleDateFormat("MMdd");
		orderNum =sdf.format(create_time)+ OrderCode.IDC_CODE.getId() + id;
		paramsMap.put("order_num", orderNum);
		orderDao.updateIdcOrderNumById(paramsMap);
		json.setResult(true);
		
		return json;
	
	}	
	
	@ResponseBody
	@RequestMapping(value = "/payorder.json", method = RequestMethod.POST)
	public JsonVo<String> payorder(HttpServletRequest request, ModelMap modelMap){
		
		double rest_money;
		createParameterMap(request);
		User user=(User)request.getSession().getAttribute("user");
		user=userDao.getUserById(user.getReg_tel());
		
		Map<String,Object> orderInfo = new HashMap<String,Object>();
		Map<String,Object> map = new HashMap<String,Object>();
		if("ISP".equals(paramsMap.get("type")))
		{
			orderInfo = orderDao.queryISPOrderById(paramsMap.get("order_id").toString());
			rest_money = Double.valueOf(user.getBalance().toString()) - Double.valueOf(orderInfo.get("cost_money").toString());
			if(rest_money>=0.0)
			{
				user.setBalance(new BigDecimal(Double.valueOf(rest_money)));	
				map.put("balance", rest_money);
				map.put("userId", user.getUser_id());
				userDao.updateBalanceById(map);
				
				paramsMap.put("status", 2); //将订单状态改为已付款状态
				orderDao.updateISPOrderStatus(paramsMap);
				
				/*****保存到账户变更日志*******/
				paramsMap.put("bank_money", 0.0-Double.valueOf(orderInfo.get("cost_money").toString()));
				paramsMap.put("user_id", user.getUser_id());
				paramsMap.put("type","3");//？？				
				paramsMap.put("order_sn", CommonUtil.CreatOrderId());
				paramsMap.put("create_time",new Date());
				paramsMap.put("description","购买ISP服务");
				paramsMap.put("status","1");
				
				paramsMap.put("kf_refund","0");//默认数据
				paramsMap.put("cw_refund","0");
				paramsMap.put("gl_name","");
				userBankLogDao.addUserBankLog(paramsMap);//创建订单
				
			}
			else
			{
				json.getErrors().put("balance","余额不足，请充值");
				json.setResult(false);
				return json;
			}
		}
		else if("IDC".equals(paramsMap.get("type")))
		{
			orderInfo = orderDao.queryIDCOrderById(paramsMap.get("order_id").toString());
			rest_money = Double.valueOf(user.getBalance().toString()) - Double.valueOf(orderInfo.get("cost_money").toString());
			if(rest_money>=0.0)
			{
				user.setBalance(new BigDecimal(Double.valueOf(rest_money)));	
				map.put("balance", rest_money);
				map.put("userId", user.getUser_id());
				userDao.updateBalanceById(map);
				
				paramsMap.put("status", 2); //将订单状态改为已付款状态
				orderDao.updateIDCOrderStatus(paramsMap);
				
				/*****保存到账户变更日志*******/
				paramsMap.put("bank_money", 0.0-Double.valueOf(orderInfo.get("cost_money").toString()));
				paramsMap.put("user_id", user.getUser_id());
				paramsMap.put("type","3");//？？				
				paramsMap.put("order_sn", CommonUtil.CreatOrderId());
				paramsMap.put("create_time",new Date());
				paramsMap.put("description","购买IDC服务");
				paramsMap.put("status","1");
				
				paramsMap.put("kf_refund","0");//默认数据
				paramsMap.put("cw_refund","0");
				paramsMap.put("gl_name","");
				userBankLogDao.addUserBankLog(paramsMap);//创建订单
			}
			else
			{
				json.getErrors().put("balance","余额不足，请充值");
				json.setResult(false);
				return json;
			}
		}
		json.setResult(true);
		return json;	
	}
	@ResponseBody
	@RequestMapping(value = "/concel_order.json", method = RequestMethod.POST)
	public JsonVo<String> concel_order(HttpServletRequest request, ModelMap modelMap){
		double rest_money;
		Map<String,Object> orderInfo = new HashMap<String,Object>();
		createParameterMap(request);
		if("ISP".equals(paramsMap.get("type")))
		{
			orderInfo = orderDao.queryISPOrderById(paramsMap.get("order_id").toString());
			if("2".equals(orderInfo.get("status").toString())) //订单为已付款状态，需要执行退款操作
			{
				User user=(User)request.getSession().getAttribute("user");
				Map<String,Object> map = new HashMap<String,Object>();
				user=userDao.getUserById(user.getReg_tel());
				rest_money = Double.valueOf(user.getBalance().toString()) + Double.valueOf(orderInfo.get("cost_money").toString());
				user.setBalance(new BigDecimal(Double.valueOf(rest_money)));	
				map.put("balance", rest_money);
				map.put("userId", user.getUser_id());
				userDao.updateBalanceById(map);		
				
				/*****保存到账户变更日志*******/
				paramsMap.put("bank_money", Double.valueOf(orderInfo.get("cost_money").toString()));
				paramsMap.put("user_id", user.getUser_id());
				paramsMap.put("type","3");//？？				
				paramsMap.put("order_sn", CommonUtil.CreatOrderId());
				paramsMap.put("create_time",new Date());
				paramsMap.put("description","ISP订单取消退款");
				paramsMap.put("status","1");
				
				paramsMap.put("kf_refund","0");//默认数据
				paramsMap.put("cw_refund","0");
				paramsMap.put("gl_name","");
				userBankLogDao.addUserBankLog(paramsMap);//创建订单
				
			}
			paramsMap.put("status", 7); //将订单状态改为取消状态
			orderDao.updateISPOrderStatus(paramsMap);
		}
		else if("IDC".equals(paramsMap.get("type")))
		{
			orderInfo = orderDao.queryIDCOrderById(paramsMap.get("order_id").toString());
			if("2".equals(orderInfo.get("status").toString())) //订单为已付款状态，需要执行退款操作
			{
				User user=(User)request.getSession().getAttribute("user");
				Map<String,Object> map = new HashMap<String,Object>();
				user=userDao.getUserById(user.getReg_tel());
				rest_money = Double.valueOf(user.getBalance().toString()) + Double.valueOf(orderInfo.get("cost_money").toString());
				user.setBalance(new BigDecimal(Double.valueOf(rest_money)));	
				map.put("balance", rest_money);
				map.put("userId", user.getUser_id());
				userDao.updateBalanceById(map);				
				/*****保存到账户变更日志*******/
				paramsMap.put("bank_money", Double.valueOf(orderInfo.get("cost_money").toString()));
				paramsMap.put("user_id", user.getUser_id());
				paramsMap.put("type","3");//？？				
				paramsMap.put("order_sn", CommonUtil.CreatOrderId());
				paramsMap.put("create_time",new Date());
				paramsMap.put("description","IDC订单取消退款");
				paramsMap.put("status","1");
				
				paramsMap.put("kf_refund","0");//默认数据
				paramsMap.put("cw_refund","0");
				paramsMap.put("gl_name","");
				userBankLogDao.addUserBankLog(paramsMap);//创建订单	
			}
			paramsMap.put("status", 7); //将订单状态改为取消状态
			orderDao.updateIDCOrderStatus(paramsMap);			
		}
		json.setResult(true);
		return json;	
	}
	@RequestMapping(value="/orderdetail.htm",method = RequestMethod.GET)
	public String orderdetail(HttpServletRequest request,ModelMap modelMap,
			@RequestParam(value = "ordertype") String orderType, @RequestParam(value = "orderid") String orderId
			){
		  Map<String,Object> orderInfo = new HashMap<String,Object>();
		  if("ISP".equals(orderType))
		  {
			  orderInfo = orderDao.queryISPOrderById(orderId);
		  }
		  else if("IDC".equals(orderType))
		  {
			  orderInfo = orderDao.queryIDCOrderById(orderId);
		  }
		  modelMap.put("orderinfo", orderInfo);

		  return "/business/orderdetail";
	}
	@RequestMapping(value="/business.htm")
	public String IDCService(HttpServletRequest request,ModelMap modelMap
			)throws Exception{
		Date date;
		int pages=0;
		int offset=0;
		int totalCount=0;

		createParameterMap(request);
		int pageNo=paramsMap.get("pageNo")!=null?Integer.valueOf(paramsMap.get("pageNo").toString()):1;
//		-------分页查询
		if("".equals(paramsMap.get("order_num")))paramsMap.remove("order_num");//""查询全部
		if("".equals(paramsMap.get("status")) || null==paramsMap.get("status") || "5".equals(paramsMap.get("status").toString()))paramsMap.remove("status");//""查询全部
		if(!"".equals(paramsMap.get("start_date1")) && null != paramsMap.get("start_date1"))
		{
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

			paramsMap.put("start_date", sdf2.format(sdf.parse(paramsMap.get("start_date1").toString()))+" 00:00:00") ;			
		}
		if(!"".equals(paramsMap.get("end_date1")) && null != paramsMap.get("end_date1") )
		{
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

			paramsMap.put("end_date", sdf2.format(sdf.parse(paramsMap.get("end_date1").toString()))+" 23:59:59") ;			
		}
//		paramsMap.put("start_date", "2016-03-26");

//		paramsMap.remove("end_date");
		pageNo=pageNo<1?1:pageNo;//页码当前为1

		User user=(User)request.getSession().getAttribute("user");
		paramsMap.put("user_id", user.getReg_tel());
		List<Map<String,Object>> orderListInfo=null;
		if(paramsMap.get("business_type")==null || "0".equals(paramsMap.get("business_type").toString())) //查询ISP和IDC订单
		{
			 totalCount = orderDao.queryISPOrderCount(paramsMap)+orderDao.queryIDCOrderCount(paramsMap);//记录总数
			 pages=totalCount%DEFAULT_COUNT_ONEPAGE==0?totalCount/DEFAULT_COUNT_ONEPAGE:totalCount/DEFAULT_COUNT_ONEPAGE+1;
				if(pageNo>pages) pageNo=pages;
				 offset=(pageNo-1)*DEFAULT_COUNT_ONEPAGE;//偏移量
				
				if(offset<0)offset=0;
				paramsMap.put("offset", offset);
				paramsMap.put("rows", DEFAULT_COUNT_ONEPAGE);

			 orderListInfo = orderDao.queryOrderByUserId(paramsMap);

		}
		else if("1".equals(paramsMap.get("business_type").toString())) //只查询ISP订单
		{
			 totalCount = orderDao.queryISPOrderCount(paramsMap);//记录总数
			 pages=totalCount%DEFAULT_COUNT_ONEPAGE==0?totalCount/DEFAULT_COUNT_ONEPAGE:totalCount/DEFAULT_COUNT_ONEPAGE+1;
				if(pageNo>pages) pageNo=pages;
				 offset=(pageNo-1)*DEFAULT_COUNT_ONEPAGE;//偏移量
				
				if(offset<0)offset=0;
				paramsMap.put("offset", offset);
				paramsMap.put("rows", DEFAULT_COUNT_ONEPAGE);

			 orderListInfo = orderDao.queryISPOrderByUserId(paramsMap);	

		}
		else   //只查询IDC订单
		{
			 totalCount = orderDao.queryIDCOrderCount(paramsMap);//记录总数
			 pages=totalCount%DEFAULT_COUNT_ONEPAGE==0?totalCount/DEFAULT_COUNT_ONEPAGE:totalCount/DEFAULT_COUNT_ONEPAGE+1;
				if(pageNo>pages) pageNo=pages;
				 offset=(pageNo-1)*DEFAULT_COUNT_ONEPAGE;//偏移量
				
				if(offset<0)offset=0;
				paramsMap.put("offset", offset);
				paramsMap.put("rows", DEFAULT_COUNT_ONEPAGE);

			orderListInfo = orderDao.queryIDCOrderByUserId(paramsMap);

		}
		
		modelMap.put("orderListInfo", orderListInfo);
		modelMap.put("pages",pages);//总页数
		modelMap.put("totalCount", totalCount);//总条数
		modelMap.put("pageNo", pageNo);//当前页号
		paramsMap.remove("pageNo");
		modelMap.putAll(paramsMap);
//		List<Map<String,Object>>   contractInfoList = contractDao.queryContractInfo(paramsMap);
//		modelMap.addAttribute("contractInfoList", contractInfoList);//用户的合同列表信息

		
		return "/business/business";//ftl文件路径
	}
	
	@RequestMapping(value="/business_detail.htm",method = RequestMethod.GET)
	public String businessdetail(HttpServletRequest request,ModelMap modelMap
			){
		User user=(User)request.getSession().getAttribute("user");
		createParameterMap(request);
		paramsMap.put("user_id", user.getReg_tel());
		paramsMap.put("status", 1);
		
		int pageNo=paramsMap.get("pageNo")!=null?Integer.valueOf(paramsMap.get("pageNo").toString()):1;
//		-------分页查询
		pageNo=pageNo<1?1:pageNo;//页码当前为1
		paramsMap.put("userId", user.getReg_tel());
		
		int totalCount = contractDao.queryContractCount(paramsMap);//记录总数
		//总页数
		int pages=totalCount%DEFAULT_COUNT_ONEPAGE==0?totalCount/DEFAULT_COUNT_ONEPAGE:totalCount/DEFAULT_COUNT_ONEPAGE+1;
//		if(pageNo<1) pageNo=1;
		if(pageNo>pages) pageNo=pages;
		int offset=(pageNo-1)*DEFAULT_COUNT_ONEPAGE;//偏移量
		
		if(offset<0)offset=0;
		paramsMap.put("offset", offset);
		paramsMap.put("rows", DEFAULT_COUNT_ONEPAGE);

		List<Map<String,Object>>   contractInfoList = contractDao.queryContractInfo(paramsMap);
		modelMap.addAttribute("contractInfoList", contractInfoList);//用户的合同列表信息
		modelMap.put("pages",pages);//总页数
		modelMap.put("totalCount", totalCount);//总条数
		modelMap.put("pageNo", pageNo);//当前页号		
		return "/business/business_detail";
	}

}
